import COS from 'cos-js-sdk-v5';

const Bucket = 'dev-1300222288';
const Region = "ap-shanghai";
const resourceUrl = "https://qcloud.resource.dev.hygeian.com.cn/";
const bucket = 'hy_client_log/';

const cos = new COS({
    SecretId: 'AKIDWrwlK3iljS9wUn5yh9NM1TfCYfaT69vV',
    SecretKey: 'aCZKsCHAsKpBJBxXrwlKgogPt75rOhkX'
})
/**
 * 上传日志
 * @param data 
 * @param name 
 * @param callback 
 */
export function uploadLogs(data: string, storeName: string, callback?: (path: string) => void) {

    const content = JSON.stringify({ items: data });
    const blob = new Blob([content], { type: "text/plain;charset=utf-8" }); // 把数据转化成blob对象
    const file = new File([blob], "filename", { lastModified: Date.now() }); // blob转file
    const name = `${storeName}.json`;

    cos.uploadFile({
        Bucket: Bucket,
        Region: Region,
        Key: bucket + name,
        Body: file,
        onProgress: (event: any) => {
            if (event.total > 0) {
                (event as any).percent = Math.round(event.loaded * 100 / event.total);
            }
        }
    }, (err: any, data: any) => {
        if (data.statusCode == 200) {
            //回调函数
            if (callback) {
                callback(resourceUrl + bucket + name + "?d=" + new Date().getTime());
            }
        }
    });
}
/**
 * 上传日志
 * @param data 
 * @param name 
 * @param callback 
 */
export function uploadLocalLogs(data: string, storeName: string, callback?: (path: string) => void) {

    const content = JSON.stringify({ items: data });
    const blob = new Blob([content], { type: "text/plain;charset=utf-8" }); // 把数据转化成blob对象
    const name = `${storeName}.json`;

    // 如果是本地环境，直接保存到本地
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = name;
    link.click();
    // 如果需要回调，可以在这里调用
    if (callback) {
        callback(`file://${name}`);
    }
}
/**
 * 获取cos文件列表
 */
export function getFils(callback: (files: any) => void) {
    cos.getBucket({
        Bucket: Bucket, // 填入您自己的存储桶，必须字段
        Region: Region,  // 存储桶所在地域，例如ap-beijing，必须字段
        Prefix: bucket,           // Prefix表示列出的object的key以prefix开始，非必须
    }, function (err, data) {
        callback(err || data.Contents);
    });
}
